package com.my.quartz.boot;

import com.my.quartz.boot.pojo.SysJob;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @Author ScholarTang
 * @Date 2021/7/14 下午4:09
 * @Desc 定时任务处理（允许并发执行）
 */
@Slf4j
@Component
public class QuartzJobImpl implements Job {

    @Autowired
    private ApplicationContext context;

    @SneakyThrows
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        SysJob sysJob = new SysJob();
        BeanUtils.copyProperties(jobExecutionContext.getMergedJobDataMap().get("QuartzJobExecutionData"), sysJob);
        log.info("正在执行任务");
        String invokeTarget = sysJob.getInvokeTarget();
        String beanName = invokeTarget.split("\\.")[0];
        String methodName = invokeTarget.split("\\.")[1];
        Object bean = context.getBean(beanName);
        Class<?> clazz = bean.getClass();
        Method method = clazz.getMethod(methodName);
        method.invoke(bean);
        log.info("已结束任务");
        System.out.println();
    }
}
